package admin

import (
	"news_for_deepseek_interface/config"
	"news_for_deepseek_interface/controller"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

func Upload(c *gin.Context) {
	file, err := c.FormFile("file")
	if err != nil {
		controller.Fail(c, controller.BusinessError, "上传文件失败")
		return
	}

	// 生成随机文件名
	now := time.Now()
	dateDir := now.Format("2006-01-02") // 生成形如 "2023-04-01" 的目录名
	randomFileName := generateRandomFileName(file.Filename)

	uploadDir := filepath.Join("uploads", dateDir)
	filePath := filepath.Join(dateDir, randomFileName)
	fullPath := filepath.Join(uploadDir, randomFileName)

	// 确保目录存在
	if err := os.MkdirAll(uploadDir, 0755); err != nil {
		controller.Fail(c, controller.BusinessError, "创建目录失败")
		return
	}

	// 将文件保存到指定路径
	if err := c.SaveUploadedFile(file, fullPath); err != nil {
		controller.Fail(c, controller.BusinessError, "保存文件失败")
		return
	}

	imgUrlPrefix := config.DefaultConfig.Server.ImageUrl
	imgUrl := strings.TrimSuffix(imgUrlPrefix, "/") + "/" + filePath
	c.JSON(200, gin.H{"image_url": imgUrl})
}

// 生成随机文件名
func generateRandomFileName(filename string) string {
	ext := filepath.Ext(filename)
	randomID := uuid.New().String()
	return randomID + ext
}
